<?php

namespace frontend\models;

use Yii;

/**
 * This is the model class for table "menu".
 *
 * @property integer $id
 * @property string $title
 * @property string $desc
 * @property string $path
 * @property integer $parent_id
 * @property string $view_permission
 * @property string $status
 *
 * @property Menu $parent
 * @property Menu[] $menus
 */
class Menu extends \yii\db\ActiveRecord
{
   public static function getMenu(){
		$menus = Menu::findAll([
			'status'	=>	'Y',
			'parent_id'	=>	NULL
		]);		
		$data = Menu::buildMenu($menus, false);
		return $data;
		// echo '<pre>';
		// print_r($data);
		// die;
	}
	
	public static function buildMenu($menus = [], $isSub = false){		
		$data = [];
		$userId	=	Yii::$app->user->identity->id;
		foreach($menus as $obj) {			
			$subs = Menu::findAll(['parent_id'	=>	$obj->id]);
			$perm = unserialize($obj->view_permission);
			if(in_array($userId, $perm) || $perm[0] === '*'){				
				if(!$subs){
					$data[] = ['label' => $obj->title, 'url' => [$obj->path]];
				}else{				
					$data[] = ['label' => $obj->title, 'items' => static::buildMenu($subs)];
				}
			}
		}
		// echo '<pre>';
		// print_r($menus);
		// die;
		return $data;
	}
	
	/**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'menu';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['title', 'path', 'view_permission', 'status'], 'required'],
            [['parent_id'], 'integer'],
            [['view_permission', 'status'], 'string'],
            [['title', 'path'], 'string', 'max' => 100],
            [['desc'], 'string', 'max' => 200]
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'title' => 'Title',
            'desc' => 'Desc',
            'path' => 'Path',
            'parent_id' => 'Parent ID',
            'view_permission' => 'View Permission',
            'status' => 'Status',
        ];
    }
	 
    /**
     * @return \yii\db\ActiveQuery
     */
    public function getParent()
    {
        return $this->hasOne(Menu::className(), ['id' => 'parent_id']);
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getMenus()
    {
        return $this->hasMany(Menu::className(), ['parent_id' => 'id']);
    }
}
